#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Diagnose cv2 installation and packaging issues
"""

import sys
import os
import importlib
from pathlib import Path

def check_cv2_installation():
    """Check cv2 installation"""
    print("=== CV2 Installation Check ===")
    
    try:
        import cv2
        print(f"? cv2 imported successfully")
        print(f"  Version: {cv2.__version__}")
        print(f"  Path: {cv2.__file__}")
        
        # Check if cv2 has the expected attributes
        if hasattr(cv2, 'imread'):
            print("? cv2.imread available")
        else:
            print("? cv2.imread not available")
            
        if hasattr(cv2, 'imwrite'):
            print("? cv2.imwrite available")
        else:
            print("? cv2.imwrite not available")
            
        return True
        
    except ImportError as e:
        print(f"? cv2 import failed: {e}")
        return False
    except Exception as e:
        print(f"? cv2 error: {e}")
        return False

def check_cv2_files():
    """Check cv2 files in site-packages"""
    print("\n=== CV2 Files Check ===")
    
    try:
        import cv2
        cv2_path = Path(cv2.__file__).parent
        
        print(f"CV2 directory: {cv2_path}")
        
        # List cv2 files
        cv2_files = list(cv2_path.glob('*'))
        print(f"Found {len(cv2_files)} files in cv2 directory:")
        
        for file in cv2_files[:10]:  # Show first 10 files
            print(f"  {file.name}")
            
        if len(cv2_files) > 10:
            print(f"  ... and {len(cv2_files) - 10} more files")
            
        # Check for DLL files
        dll_files = list(cv2_path.glob('*.dll'))
        pyd_files = list(cv2_path.glob('*.pyd'))
        
        print(f"\nDLL files: {len(dll_files)}")
        print(f"PYD files: {len(pyd_files)}")
        
        return True
        
    except Exception as e:
        print(f"? Error checking cv2 files: {e}")
        return False

def check_pyinstaller_hooks():
    """Check if PyInstaller hooks exist for cv2"""
    print("\n=== PyInstaller Hooks Check ===")
    
    try:
        import PyInstaller
        pyinstaller_path = Path(PyInstaller.__file__).parent / 'hooks'
        
        if pyinstaller_path.exists():
            print(f"PyInstaller hooks directory: {pyinstaller_path}")
            
            # Check for cv2 hook
            cv2_hook = pyinstaller_path / 'hook-cv2.py'
            if cv2_hook.exists():
                print("? hook-cv2.py found")
            else:
                print("? hook-cv2.py not found")
                
            # List available hooks
            hooks = list(pyinstaller_path.glob('hook-*.py'))
            print(f"Total hooks found: {len(hooks)}")
            
        else:
            print("? PyInstaller hooks directory not found")
            
        return True
        
    except Exception as e:
        print(f"? Error checking PyInstaller hooks: {e}")
        return False

def create_cv2_hook():
    """Create a custom cv2 hook"""
    print("\n=== Creating Custom CV2 Hook ===")
    
    hook_content = '''# -*- coding: utf-8 -*-
"""
Custom hook for cv2
"""
from PyInstaller.utils.hooks import collect_data_files, collect_submodules

# Collect all cv2 submodules
hiddenimports = collect_submodules('cv2')

# Collect cv2 data files
datas = collect_data_files('cv2')

# Add specific cv2 imports
hiddenimports += [
    'cv2',
    'cv2.cv2',
    'cv2.cv2.cv2',
    'cv2.cv2.cv2.cv2',
]

print(f"CV2 hook: {len(hiddenimports)} hidden imports, {len(datas)} data files")
'''
    
    try:
        with open('hook-cv2.py', 'w', encoding='utf-8') as f:
            f.write(hook_content)
        print("? Custom hook-cv2.py created")
        return True
    except Exception as e:
        print(f"? Error creating hook: {e}")
        return False

def main():
    """Main function"""
    print("CV2 Diagnosis Tool")
    print("=" * 60)
    
    # Check cv2 installation
    cv2_ok = check_cv2_installation()
    
    # Check cv2 files
    files_ok = check_cv2_files()
    
    # Check PyInstaller hooks
    hooks_ok = check_pyinstaller_hooks()
    
    # Create custom hook
    hook_created = create_cv2_hook()
    
    print("\n" + "=" * 60)
    print("SUMMARY:")
    print(f"CV2 Installation: {'?' if cv2_ok else '?'}")
    print(f"CV2 Files: {'?' if files_ok else '?'}")
    print(f"PyInstaller Hooks: {'?' if hooks_ok else '?'}")
    print(f"Custom Hook Created: {'?' if hook_created else '?'}")
    
    if cv2_ok and files_ok:
        print("\n? CV2 appears to be properly installed")
        print("Try using build_with_hooks.bat for packaging")
    else:
        print("\n? CV2 has issues")
        print("Try reinstalling opencv-python:")
        print("pip uninstall opencv-python")
        print("pip install opencv-python")

if __name__ == "__main__":
    main() 